import { getRandom } from './util.js'
// 实物类
class Food {
  // 构造器
  constructor({ x = 0, y = 0, width = 20, height = 20, color = 'green' } = {}) {
    // 存储器
    this.element = []
    // 数据初始化
    this.x = x
    this.y = y
    this.width = width
    this.height = height
    this.color = color
  }
  // 渲染函数
  render (map) {
    this.remove() // 添加之前先删除已存在的食物

    this.x = getRandom(0, map.offsetWidth / this.width) * this.width
    this.y = getRandom(0, map.offsetHeight / this.height) * this.height

    let div = document.createElement('div')
    map.appendChild(div)

    this.element.push(div)
    // 设置div样式
    div.style.position = 'absolute'
    div.style.left = this.x + 'px'
    div.style.top = this.y + 'px'
    div.style.width = this.width + 'px'
    div.style.height = this.height + 'px'
    div.style.backgroundColor = this.color
  }

  // 删除之前保存的食物
  remove () {
    let length = this.element.length
    if (length > 0) {
      for (let i = 0; i < length; i++) {
        this.element[i].parentNode.removeChild(this.element[i])
        this.element.splice(i, 1)
      }
    }
  }
}

export default Food
